package cn.com.lyb;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

public class FTPFileFetcher {

    private FTPClient ftpClient;

    public FTPFileFetcher() {
        ftpClient = new FTPClient();
    }


    public void connectAndLogin(String server, int port, String user, String password) throws IOException {
        ftpClient.connect(server, port);
        ftpClient.login(user, password);
        ftpClient.enterLocalPassiveMode();
        //ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.changeWorkingDirectory("/home/vsftpd/ftp");

    }


    public void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }


    public List<FTPFile> fetchMatchingFiles(String ftpPath, String regex, String fileExtension) throws IOException {
        List<FTPFile> matchingFiles = new ArrayList<>();
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        FTPFile[] files = ftpClient.listFiles();
        System.out.println("Files in " + ftpPath + ":");
        Pattern pattern = Pattern.compile(regex);
        OutputStream outputStream = null;
        for (FTPFile file : files) {
            if (file.isFile()) {
                String fileName = file.getName();
                if (pattern.matcher(fileName).matches() && fileName.endsWith("." + fileExtension)) {
                    String s = ftpPath + "/" + fileName;
                    FileOutputStream out = new FileOutputStream("D:\\logs\\15\\2.txt", true);
                    InputStream in = ftpClient.retrieveFileStream(fileName);

                    byte[] bytes = new byte[1024];
                    long localSize = 0L;
                    int c;
                    Date before = new Date();
                    while ((c = in.read(bytes)) != -1) {
                        out.write(bytes, 0, c);
                        localSize += c;
                        Date after = new Date();
                        //每20秒记录进度
                        if (after.getTime() - before.getTime() >= 20000) {
                            before = after;
                            //logger.info("文件：{},已经下载了：{}%", sourceFilePathName, String.format("%.2f", localSize / (assetDetail.getFileSize() + 0f) * 100 / 2));
                        }
                    }
                    in.close();
                    out.close();
                    ftpClient.completePendingCommand();

//                    System.out.println("===="+ftpPath +"/"+ file.getName());
//                    try {
//                        String s = ftpPath + "/" + fileName;
//                        outputStream = Files.newOutputStream(Paths.get("D:\\logs\\15\\2.txt"));
//                        // ftp默认使用ISO-8859-1编码格式,所以这里需要转换为ISO-8859-1，“解决文件名为中文时，下载后为空文件的问题”
//                        String remoteFileName = new String(s.getBytes("GBK"), StandardCharsets.ISO_8859_1);
//                        boolean b = ftpClient.retrieveFile(remoteFileName, outputStream);
//                        if(!b){
//                            throw new IOException("sssssssssssss");
//                        }
//
//                    }catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    matchingFiles.add(file);
                }
            }
         }
        return matchingFiles;
    }

    public static void main(String[] args) {
        FTPFileFetcher fetcher = new FTPFileFetcher();
        try {
            fetcher.connectAndLogin("172.32.1.187", 21, "ftp", "yx_jshkhsYf1Oks");
            String ftpPath = "/home/vsftpd/ftp"; // The path on the FTP server to search
            String regex = "^1.*"; // Example regex for file name matching
            String fileExtension = "txt"; // File extension to match
            List<FTPFile> matchingFiles = fetcher.fetchMatchingFiles(ftpPath, regex, fileExtension);
            for (FTPFile file : matchingFiles) {
                System.out.println("Found matching file: " + file.getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fetcher.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

